<template>
  <pro-table
    ref="table"
    title="CDK列表"
    :request="getList"
    :columns="columns"
    :search="searchConfig"
    :pagination="paginationConfig"
    @selectionChange="handleSelectionChange"
  >
    <!-- 工具栏 -->
    <template #toolbar>
      <el-button type="primary" icon="el-icon-delete" @click="batchDelete">
        批量删除
      </el-button>
      <el-button
        type="primary"
        icon="el-icon-plus"
        @click="add"
      >
        添加
      </el-button>
      <el-button type="primary" icon="el-icon-refresh" @click="refresh">
        刷新
      </el-button>
    </template>
    <template #operate="scope">
      <el-popconfirm title="Are you sure to delete this?" @confirm="delCdk(scope.row.id)">
        <template #reference>
          <el-button size="mini" type="danger">Delete</el-button>
        </template>
      </el-popconfirm>
    </template>

    <template #use="scope">
      <span v-if="scope.row.use_id !== 0">{{arrToName(scope.row.use_id)}}</span>
      <span v-else>未使用</span>
    </template>
  </pro-table>


  <el-dialog
    v-model="addVisible"
    title="新增CDK"
    width="380px"
  >
    <!--    表单-->
    <el-form
      ref="ruleFormRef"
      :model="addCdk.item"
      :rules="addCdk.rules"
      label-width="80px"
      class="demo-ruleForm"
    >
      <el-form-item label="CDK类型" prop="type">
        <el-radio-group v-model="addCdk.item.type">
          <el-radio-button label="加速器月卡"></el-radio-button>
<!--          <el-radio-button label="Washington"></el-radio-button>-->
        </el-radio-group>
      </el-form-item>
      <el-form-item label="CDK条目" prop="content">
        <el-input
          v-model="addCdk.item.content"
          :rows="5"
          type="textarea"
          placeholder="请输入CDK，一条一行"
        />
      </el-form-item>
    </el-form>
    <template #footer>
      <span class="dialog-footer">
        <el-button @click="addVisible = false">Cancel</el-button>
        <el-button type="primary" @click="submitForm('ruleFormRef')">Confirm</el-button>
      </span>
    </template>
  </el-dialog>
</template>

<script>
import { defineComponent, reactive, ref, toRefs } from "vue";
import { addCdks, delCdks, getCdkList } from "../../api/cdk";
import { ElMessage, ElMessageBox } from "element-plus";

export default defineComponent({
  name: 'cdkList',
  setup() {
    const state = reactive({
      addCdk: {
        item: {
          type: '',
          content: '',
          expire: 3,
        },
        rules: {
          type: [
            {
              required: true,
              message: '请选择CDK类型',
              trigger: 'change',
            },
          ],
          content: [
            {
              required: true,
              message: '请输入CDK,一条一行',
              trigger: 'blur',
            },
          ],

        },
      },
      ruleFormRef: ref(),
      addVisible: ref(false),
      // 表格列配置，大部分属性跟el-table-column配置一样
      columns: [
        { type: 'selection' },
        { label: '序号', prop: 'id', width: '80px' },
        { label: 'CDK', prop: 'content', sortable: true },
        { label: '使用者', tdSlot: 'use' },
        { label: '创建日期', prop: 'create_time' },
        {
          label: '操作',
          fixed: 'right',
          width: 80,
          align: 'left',
          tdSlot: 'operate', // 自定义单元格内容的插槽名称
        },
      ],
      // 搜索配置
      searchConfig: {
        labelWidth: '90px', // 必须带上单位
        inputWidth: '360px', // 必须带上单位
        fields: [
          {
            label: '状态',
            name: 'use_id',
            type: 'select',
            options: [
              {
                name: '',
                value: '',
              },
              {
                name: '已使用',
                value: 1,
              },
              {
                name: '未使用',
                value: 0,
              },
            ],
          },
          {
            label: '创建日期',
            name: 'daterange',
            type: 'daterange',
            trueNames: ['startDate', 'endDate'],
          },
        ],
      },
      // 分页配置
      paginationConfig: {
        layout: 'total, prev, pager, next, sizes', // 分页组件显示哪些功能
        pageSize: 5, // 每页条数
        pageSizes: [5, 10, 20, 50],
        style: { textAlign: 'left' },
      },
      selectedItems: [],
      batchDelete() {
        let arr = []
        state.selectedItems.map(item => {
          arr.push(item.id)
        })
        if(arr.length > 0){
          ElMessageBox.confirm(
            '此操作将会删除所选中的条目，Are you sure?',
            'Warning',
            {
              confirmButtonText: 'YES',
              cancelButtonText: 'NO',
              type: 'warning',
            }
          ).then(() => { methods.delCdk(arr)})
        } else {
          ElMessage({
            message: '你没有选中任何条目！',
            type: 'error',
          })
        }
      },
      // 选择
      handleSelectionChange(arr) {
        state.selectedItems = arr
      },
      // 请求函数
      async getList(params) {
        // params是从组件接收的，包含分页和搜索字段。
        const { data } = await getCdkList(params)

        // 必须要返回一个对象，包含data数组和total总数
        return {
          data: data.list,
          total: +data.total,
        }
      },
    })
    const table = ref(null)
    const refresh = () => {
      table.value.refresh()
    }
    const methods = {
      async delCdk(cid) {
        let resp = await delCdks(cid)
        if (resp.code !== 200) {
          ElMessage({
            message: resp.message || '服务器错误！',
            type: 'error',
          })
        } else {
          table.value.refresh()
          ElMessage({
            message: resp.message || 'ok',
            type: 'success',
          })
        }
      },
      submitForm(formName) {
        this.$refs[formName].validate(async (valid) => {
          if (valid) {
            let resp = await addCdks(state.addCdk.item)
            if (resp.code !== 200) {
              ElMessage({
                message: resp.message || '服务器错误！',
                type: 'error',
              })
            } else {
              state.addVisible = false
              state.addCdk.item = {
                type: '',
                content: '',
                expire: 3,
              }
              table.value.refresh()
              ElMessage({
                message: resp.message || 'ok',
                type: 'success',
              })
            }
          } else {
            return false
          }
        })
      },
      add() {
        state.addCdk.item = {
          name: '',
          count: 0,
          scale: 0,
        }
        state.addVisible = true
      },
      edit(data) {
        state.addVisible = true
        state.addCdk.item = {
          id: data.id,
          name: data.name,
          count: data.count,
          scale: data.scale,
        }
        console.log(state.addCdk.item)
      },
      arrToName(v) {
        return '[ ' + v.team + ' ] ' + v.nickname
      },
    }
    return { ...toRefs(state), refresh, table, ...methods }
  },
})
</script>
